<?php

namespace app\model;

use app\BaseModel;

/**
 * 权限规则
 */
class AuthRuleModel extends BaseModel
{
    protected $name = 'auth_rule';

    public function addValidate(): array
    {
        return [
            'url|菜单地址'  => 'require',
            'name|名称'  => 'require',
//            'type_id|类型'  => 'require',
        ];
    }

    /**
     * 获取所有权限
     * @param array $where
     * @param string $field
     * @return mixed
     */
    public function getAllMenu(array $where=[],string $field=''): mixed
    {
        if (empty($field)){
            $field = 'id,pid,name,url,icon,icon_shortcut,icon_task,sort,induce,mode,status,type,c_type,type_id,is_must,is_must1,is_must2,is_must3';
        }
        $menu = $this->field($field)
            ->where($where)->order('sort asc,id asc')->select()->toArray();
        $back = array();
        foreach ($menu as $v){
            $back[$v['id']]=$v;
        }
        $back[0]=[];
        foreach ($back as &$item){
            if (isset($item['pid'])){
                $back[$item['pid']]['child'][]=&$item;
            }
        }
        return $back[0]['child']??[];
    }

    /**
     * 获取菜单权限
     * @param string $rule 权限
     * @return mixed
     */
    public function getMenu(string $rule): mixed
    {
        if (empty($rule)) return [];
        $rule = explode(',',$rule);
        $where = [];
        $where[] = ['id', 'in', $rule];
        $where[] = ['status', '=', 1];
        $menu = $this->field('id,pid,name,url,icon,icon_shortcut,icon_task,sort,is_must,induce,mode,status,type,type_id,c_type')
            ->where($where)->order('sort asc,id asc')->select()->toArray();
        $back = array();
        foreach ($menu as $v){
            $back[$v['id']]=$v;
        }

        $back[0]=[];
        foreach ($back as &$item){
            if (isset($item['pid'])){
                $back[$item['pid']]['child'][]=&$item;
            }
        }
        return $back[0]['child']??[];
    }
}